package csu.web.jpetstore.web.servlet;

import csu.web.jpetstore.domain.Item;
import csu.web.jpetstore.domain.Product;
import csu.web.jpetstore.persistence.impl.LoggerDAOImpl;
import csu.web.jpetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

import static csu.web.jpetstore.persistence.impl.LoggerDAOImpl.loginLogger;

public class ItemViewServlet extends HttpServlet {

    private CatalogService catalogService;

    private static final String ITEM_VIEW= "/WEB-INF/jsp/catalog/item.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String itemId = req.getParameter("itemId");
        LoggerDAOImpl loggerDAO=new LoggerDAOImpl();
        loginLogger.setStarttime();
        loginLogger.setAction(loginLogger.getUsername()+"查看"+itemId+"详情");
        try {
            loggerDAO.logger(loginLogger);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        catalogService = new CatalogService();
        Item item = catalogService.getItem(itemId);
        Product product = item.getProduct();
        HttpSession session = req.getSession();
        session.setAttribute("product", product);
        session.setAttribute("item", item);//改成req的做法，避免cart刷新数量+1的bug
        req.getRequestDispatcher(ITEM_VIEW).forward(req, resp);
    }
}
